package com.briup.pts.web.controller;

import com.briup.pts.config.auth.SecurityUserContext;
import com.briup.pts.config.auth.TokenMapContext;
import com.briup.pts.config.response.Result;
import com.briup.pts.domain.bean.Account;
import com.briup.pts.domain.dto.UserLoginDTO;
import com.briup.pts.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterStyle;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
@Tag(name = "认证模块")
@RestController
@RequiredArgsConstructor
public class AuthController {
    private final UserService userService;

    @Operation(summary = "登录接口",parameters = {
            @Parameter(name = "username",required = true,style = ParameterStyle.FORM),
            @Parameter(name = "password",required = true,style = ParameterStyle.FORM)
    })
    @PostMapping("/login")
    public Result<?> login(@Valid UserLoginDTO loginDTO) {
        Map<String, String> map = userService.login(loginDTO);
        return Result.success(map);
    }

    @Operation(summary = "退出登录接口")
    @GetMapping("/logout")
    public Result<?> logout() {
        // 从认证上下文中获取当前登录用户的id
        String userId = SecurityUserContext.userId();
        // 根据id移除内存中存储的当前用户的token
        TokenMapContext.remove(userId);
        return Result.success();
    }

    @Operation(summary = "获取当前登录用户信息接口")
    @GetMapping("/me")
    public Result<?> me() {
        Account account = SecurityUserContext.currentUser();
        return Result.success(account);
    }
}
